<template>
  <div id="three"></div>
</template>

<script>
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
let elementResizeDetector = require("element-resize-detector");

export default {
  mounted() {
    this.init();
  },
  data() {
    return {};
  },
  methods: {
    init() {
      //创建场景
      const scene = new THREE.Scene();
      //长方体
      const geometry = new THREE.BoxGeometry(100, 100, 100);
      const material = new THREE.MeshLambertMaterial({
        color: "#6cf",
        transparent: true,
        opacity: 0.8,
      });
      //网格模型
      const mesh = new THREE.Mesh(geometry, material);
      scene.add(mesh);
      mesh.position.set(50,50,50) //位置
      mesh.rotateY(Math.PI/4) //旋转
      //光
      //环境光
      const ambient = new THREE.AmbientLight("#fff", 0.5);
      ambient.position.set(200, 200, 200);
      scene.add(ambient);
      //点光源
      const pointLight = new THREE.PointLight("#fff", 0.5);
      pointLight.position.set(200, 200, 200);
      scene.add(pointLight);
      //点光源可视化
      const pointLightHelper = new THREE.PointLightHelper(pointLight, 10);
      scene.add(pointLightHelper);
      //坐标轴
      const axesHelper = new THREE.AxesHelper(100);
      scene.add(axesHelper);
      //相机
      let width = document.getElementById("three").clientWidth;
      let height = document.getElementById("three").clientHeight;
      const camera = new THREE.PerspectiveCamera(45, width / height, 1, 1000);
      //相机位置
      camera.position.set(200, 200, 200);
      //目标位置
      camera.lookAt(0, 0, 0);
      //渲染器
      const renderer = new THREE.WebGLRenderer();
      renderer.setSize(width, height);
      //渲染
      renderer.render(scene, camera);
      document.getElementById("three").appendChild(renderer.domElement);
      //轨道控制器
      const controls = new OrbitControls(camera, renderer.domElement);
      controls.addEventListener("change", () => {
        renderer.render(scene, camera);
      });
      //监听变化
      const erd = elementResizeDetector();
      erd.listenTo(document.getElementById("three"), () => {
        width = document.getElementById("three").clientWidth;
        height = document.getElementById("three").clientHeight;
        camera.aspect = width/height
        camera.updateProjectionMatrix()
        renderer.setSize(width, height);
        renderer.render(scene, camera);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
#three {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
</style>